/**
* name: http服务
* describe: 对http请求做统一处理
*/
import { Injectable, Optional } from '@angular/core';
import { Http, Response, Headers } from '@angular/http';
import { RequestOptions, ResponseContentType } from '@angular/http';
import { SessionStorage } from '../../tools/session.storage';
import 'rxjs/add/operator/toPromise';
import { UniConfigService } from '../config/uni-config.service';
@Injectable()
export class HttpInterceptorService {
  // constructor(private http: Http , private config: UniConfigService) { }
  // 需要请求的后端url
  requestUrl: string;
  responseType: number;
  constructor(
    private http: Http,
    private config: UniConfigService,
    @Optional() public authHeaders: Headers,
    @Optional() public storage: SessionStorage) {
  }
  public requestExt(params: any): any {
    this.requestUrl = this.config.HOSTURL_EXT;
    return this.excuteRequest(params);
  }

  public requestBidExt(params: any): any {
    this.requestUrl = this.config.HOSTURL_BID_EXT;
    return this.excuteRequest(params);
  }

  /**
   * 请求H04-开标查询后端
   * @param params
   */
  public requestOpenbidData(params: any): any {
    this.requestUrl = this.config.HOSTURL_OPENBID_DATA;
    return this.excuteRequest(params);
  }

  /**
  * @param params
  */
  public requestBid(params: any): any {
    this.requestUrl = this.config.HOSTURL_BID;
    return this.excuteRequest(params);
  }

  /**
   * @param params 请求参数
   */
  public request(params: any): any {
    this.requestUrl = this.config.HOSTURL;
    return this.excuteRequest(params);
  }

  /**
   * 请求H03-中标结果查询后端
   * @param params 请求参数
   */
  public requestFor Win(params: any): any {
    this.requestUrl = this.config.HOSTURL_WIN;
    return this.excuteRequest(params);
  }

  /**
   * 请求供应商资质业绩凭证单后端
   * @param params 请求参数
   */
  public requestForSuppExt(params: any): any {
    this.requestUrl = this.config.HOSTURL_SUPP_EXT;
    return this.excuteRequest(params);
  }

 /**
   * 请求 _bid后端
   * @param params 请求参数
   */
  public requestFor Bid(params: any): any {
    this.requestUrl = this.config.HOSTURL_ _BID;
    return this.excuteRequest(params);
  }

  /**
   * 请求H08-竞拍和竞价后端
   * @param params 请求参数
   */
  public request Bid(params: any): any {
    this.requestUrl = this.config.HOSTURL_ _BID;
    return this.excuteRequest(params);
  }

  public requestSys(params: any): any {
    this.requestUrl = this.config.HOSTURL_SYS;
    return this.excuteRequest(params);
  }
  /**
  * 统一发送请求
  * @param params
  * @returns {Promise<{success: boolean, msg: string}>|Promise<R>}
  */
  private excuteRequest(params: any): any {
    this.storage = new SessionStorage();
    this.authHeaders = new Headers();
    this.setToken(params);
    //判断是否有文件下载需求
    if (params['responseType'] != null && params['responseType'] != undefined && params['responseType'] != '' && params['responseType'] === 'blob') {
      this.responseType = ResponseContentType.Blob
    } else {
      //否则，把参数设置为undefined，不然下载完文件后会出现数据请求错误
      this.responseType = undefined;
    }
    // POST请求（参数、返回值类型都是任意类型)
    params['url'] = this.requestUrl + params['url'];
    //  params['url'] = params['url'];
    // console.log(params['url']);
    if (params['method'] === 'post' || params['method'] === 'POST') {
      return this.post(params['url'], params['data']);
    } else if (params['method'] === 'get' || params['method'] === 'GET') {
      // 其他请求
      return this.get(params['url'], params['data']);
    } else if (params['method'] === 'delete' || params['method'] === 'DELETE') {
      return this.delete(params['url']);
    } else if (params['method'] === 'deleteByParam') {
      return this.deleteByParam(params['url'], params['header'], params['data']);
    } else {
      return this.update(params['url'], params['data']);
    }
  }
  /**
   * get请求
   * @param url 接口地址
   * @param params 参数传递
   * @returns {Promise<R>|Promise<U>}
   */
  public get(url: string, params: any): any {
    return this.http.get(url, { search: params })
      .toPromise()
      .then(this.handleSuccess)
      .catch(res => this.handleError(res));
  }
  /**
   * post请求
   * @param url 接口地址
   * @param params 参数
   * @returns {Promise<R>|Promise<U>}
   */
  public post(url: string, params: any) {
    // token 加入header里
    let options = new RequestOptions({ headers: this.authHeaders });
    //适配文件下载
    if (this.responseType != null && this.responseType != undefined) {
      options = new RequestOptions({ headers: this.authHeaders, responseType: this.responseType });
    }
    return this.http.post(url, params, options)
      .toPromise()
      .then(this.handleSuccess)
      .catch(res => this.handleError(res));
  }

  /**
   * update请求
   * @param url 接口地址
   * @param params 参数
   * @returns {Promise<R>|Promise<U>}
   */
  public update(url: string, params: any) {
    // token 加入header里
    let options = new RequestOptions({ headers: this.authHeaders });
    return this.http.put(url, params, options)
      .toPromise()
      .then(this.handleSuccess)
      .catch(res => this.handleError(res));
  }
  /**
  * delete 请求
  * @param url 接口地址
  * @param params 参数
  * @returns {Promise<R>|Promise<U>}
  */
  public delete(url: string) {
    // token 加入header里
    let options = new RequestOptions({ headers: this.authHeaders });
    return this.http.delete(url, options)
      .toPromise()
      .then(this.handleSuccess)
      .catch(res => this.handleError(res));
  }

  /**
   * delete 带body传参
   * @param {string} url
   * @param headers
   * @param params
   * @returns {Promise<{success: boolean; msg: string} | never | Response>}
   */
  public deleteByParam(url: string, headers: any, params: any) {
    return this.http.delete(url, new RequestOptions({
      headers: this.authHeaders,
      body: params
    }))
      .toPromise()
      .then(this.handleSuccess)
      .catch(res => this.handleError(res));
  }
  /**
   * 处理请求成功
   * @param res
   * @returns {{data: (string|null|((node:any)=>any)}}
 */
  private handleSuccess(res: Response) {
    let body = res['_body'];
    // console.log("接口返回的成功信息：" + body)
    if (body) {
      // 有数据返回
      return {
        resultValue: res.json().resultValue,
        body: body,
        data: res.json().data || {}, // 返回内容
        code: res.json().code || {}, // 返回code
        message: res.json().message || {}, // 返回信息
        statusText: res.statusText,
        status: res.status,
        resultHint: res.json().resultHint,
        type: res.json().type,
        success: res.json().successful
      };
    } else { // 无数据返回
      return {
        data: res.json().data || {}, // 返回内容
        code: res.json().code || {}, // 返回code
        message: res.json().message || {}, // 返回信息
        statusText: res.statusText,
        status: res.status,
        success: true
      };
    }
  }
  /**
   * 处理请求错误
   * @param error
   * @returns {void|Promise<string>|Promise<T>|any}
   */
  private handleError(error) {
    console.log(error);
    let msg = '请求失败，可能用户登录超时，或微服务不可用。';
    if (error.status === 400) {
      console.log('请求参数正确');
    }
    if (error.status === 404) {
      console.error('请检查路径是否正确');
    }
    if (error.status === 500) {
      console.error('请求的服务器错误');
    }
    console.log(error);
    return { success: false, msg: msg };
  }

  /**
   * setToken
   * @param error
   * @returns {void|Promise<string>|Promise<T>|any}
   */
  // private setToken(params) {
  //   let token = this.storage.get('token');
  //   console.log('token====' + token);
  //   console.log(token || 'notoken');
  //   if (token !== undefined && token !== 'null') {
  //     // 设置header
  //     this.authHeaders.append('token', token);
  //     // 设置body
  //     if (params['data'] === null || params['data'] === undefined || params['data'] === '') {
  //       params['data'] = {};
  //     }
  //     params['data']['token'] = token;
  //   }
  // }

  /**
   * setToken
   * @param error
   * @returns {void|Promise<string>|Promise<T>|any}
   */
  private setToken(params) {
    var tokenObject;
    var tokenId;
    // 用户账号身份类型
    var sysFlag;
    // var param = {
    //   'tokenId':'123445'
    // };
    //
    // this.storage.setJson('token',param);
    tokenObject = this.storage.getJson('token');
    if (tokenObject === null || JSON.stringify(tokenObject) === '{}') {
      // demo
      tokenId = 'cf4cc850-1fde-41f4-9434-a2dde06339c5';
    } else {
      tokenId = tokenObject['tokenId'];
      sysFlag = tokenObject['sysFlag'];
    }

    let pageFromIndex = this.config.getProcType() + '@bidding';
    if (pageFromIndex == undefined) {
      pageFromIndex = '1@bidding';
    }
    // header
    this.authHeaders.append('token', tokenId);
    this.authHeaders.append('pageFromIndex', pageFromIndex);
    // 添加用户账号身份类型20190822 by wujianhai
    this.authHeaders.append('sysFlag', sysFlag);
    // body
    if (params['data'] === null || params['data'] === undefined || params['data'] === '') {
      params['data'] = {};
    }
    params['data']['token'] = tokenId;
    params['data']['pageFromIndex'] = pageFromIndex;
    params['data']['sysFlag'] = sysFlag;
  }
  
}
